package cn.gbase.jiangsu.data.transfer.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.QueryResult;
import org.nutz.dao.impl.sql.SqlTemplate;
import org.nutz.dao.pager.Pager;
import org.nutz.dao.sql.Criteria;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.service.IdEntityService;

import cn.gbase.jiangsu.data.transfer.bean.Community;
import cn.gbase.jiangsu.data.transfer.bean.Company;
import cn.gbase.jiangsu.data.transfer.bean.CompanyToBuilding;
import cn.gbase.jiangsu.data.transfer.bean.CompanyToSchoolUser;
import cn.gbase.jiangsu.data.transfer.bean.CompanyUser;
import cn.gbase.jiangsu.data.transfer.bean.GoodsOrder;
import cn.gbase.jiangsu.data.transfer.bean.OperatorsToCompanyAccounts;
import cn.gbase.jiangsu.data.transfer.bean.OperatorsToSupplierAccounts;
import cn.gbase.jiangsu.data.transfer.bean.OrderSupplierView;
import cn.gbase.jiangsu.data.transfer.bean.ProductSortTree;
import cn.gbase.jiangsu.data.transfer.bean.ShopUserView;
import cn.gbase.jiangsu.data.transfer.bean.StartEndDate;
import cn.gbase.jiangsu.data.transfer.bean.StartEndDateCompany;
import cn.gbase.jiangsu.data.transfer.bean.Supplier;
import cn.gbase.jiangsu.data.transfer.bean.SupplierUser;
import cn.gbase.jiangsu.data.transfer.bean.VCompanyCommunity;
import cn.gbase.jiangsu.data.transfer.common.Constants;
import cn.gbase.jiangsu.data.transfer.util.DateUtil;
import cn.gbase.jiangsu.data.transfer.util.SystemContext;

@IocBean(args = { "refer:dao" })
public class CompanyCountService extends IdEntityService<OrderSupplierView> {

	@Inject("java:$config.get('sumDelivery')")
	private String sumDeliveryPercent;

	public CompanyCountService() {
		super();
	}

	public CompanyCountService(Dao dao) {
		super(dao);
	}

	public void sned() {
		System.out.print("111");
	}

	//计算当前物业公司下面的所有小区的商品分成总和
	public BigDecimal wygsFwfCount(CompanyUser companyUser, Cnd cnd) {
		Company company = this.dao().fetch(Company.class, Cnd.where("id", "=", companyUser.getCompanyId()));
		//先查出来该社区服务站下面的所有楼栋的ID
		List<VCompanyCommunity> vCompanyCommunityList = this.dao().query(VCompanyCommunity.class,
				Cnd.where("company_id", "=", companyUser.getId()));
		String buildingIdStr = "";
		for (VCompanyCommunity vCompanyCommunity : vCompanyCommunityList) {
			buildingIdStr += vCompanyCommunity.getBuildingId() + ",";
		}
		String buildingIdStrNew = "";
		if (buildingIdStr.equals("")) {
			buildingIdStrNew = "0";
		} else {
			buildingIdStrNew = buildingIdStr.substring(0, buildingIdStr.length() - 1);
		}
		//再查出来所有楼栋的所有用户
		List<ShopUserView> shopUserViewList = this.dao().query(ShopUserView.class,
				Cnd.where("buildingId", "in", buildingIdStrNew));
		String userIdStr = "";
		for (ShopUserView shopUserView : shopUserViewList) {
			userIdStr = shopUserView.getId() + ",";
		}
		String userIdStrNew = "";
		if (userIdStr.equals("")) {
			userIdStrNew = "0";
		} else {
			userIdStrNew = userIdStr.substring(0, userIdStr.length() - 1);
		}
		//再查出来所有用户对应的所有订单的总钱数
		BigDecimal sellPriceSum = new BigDecimal(0.0);
		BigDecimal zzSum = new BigDecimal(0.0);
		List<OrderSupplierView> orderSupplierViewList = this.dao().query(OrderSupplierView.class,
				cnd.and("user_id", "in", userIdStrNew).and("treeId", "=", "1"));
		if (orderSupplierViewList.size() != 0) {
			for (OrderSupplierView orderSupplierView : orderSupplierViewList) {
				sellPriceSum.add(orderSupplierView.getSellPrice());
			}
			//算出来的商品总数再去乘以当前小区的物业分成比例
			zzSum = sellPriceSum.multiply(new BigDecimal(company.getSharePercent())).multiply(new BigDecimal(0.01));
		}
		return zzSum;
	}

	//查询物业服务费总数
	public BigDecimal wygsSpCount(CompanyUser companyUser, Cnd cnd) {
		//先查出来登录人所对应的服务站ID，在通过服务站ID插出来服务数的treeId
		Company company = this.dao().fetch(Company.class, Cnd.where("id", "=", companyUser.getCompanyId()));
		ProductSortTree productSortTree = this.dao().fetch(ProductSortTree.class,
				Cnd.where("company_id", "=", company.getId()));

		BigDecimal sellPriceSum = new BigDecimal(0.0);
		List<OrderSupplierView> orderSupplierViewList = this.dao().query(OrderSupplierView.class,
				cnd.and("treeId", "=", productSortTree.getId()));
		for (OrderSupplierView orderSupplierView : orderSupplierViewList) {
			sellPriceSum.add(orderSupplierView.getSellPrice());
		}
		return sellPriceSum;
	}

	//算出来当前社区服务站一共有多少比订单是配送方式的
	public BigDecimal ddSumCount(CompanyUser companyUser, Cnd cnd) {
		//先查出来该社区服务站下面的所有楼栋的ID
		List<VCompanyCommunity> vCompanyCommunityList = this.dao().query(VCompanyCommunity.class,
				Cnd.where("company_id", "=", companyUser.getId()));
		String buildingIdStr = "";
		for (VCompanyCommunity vCompanyCommunity : vCompanyCommunityList) {
			buildingIdStr += vCompanyCommunity.getBuildingId() + ",";
		}
		String buildingIdStrNew = "";
		if (buildingIdStr.equals("")) {
			buildingIdStrNew = "0";
		} else {
			buildingIdStrNew = buildingIdStr.substring(0, buildingIdStr.length() - 1);
		}
		//再查出来所有楼栋的所有用户
		List<ShopUserView> shopUserViewList = this.dao().query(ShopUserView.class,
				Cnd.where("buildingId", "in", buildingIdStrNew));
		String userIdStr = "";
		for (ShopUserView shopUserView : shopUserViewList) {
			userIdStr = shopUserView.getId() + ",";
		}
		String userIdStrNew = "";
		if (userIdStrNew.equals("")) {
			userIdStrNew = "0";
		} else {
			userIdStrNew = userIdStr.substring(0, userIdStr.length() - 1);
		}
		//再查出来所有用户对应的商品运送费用
		BigDecimal deliveryPriceSum = new BigDecimal(0.0);
		List<GoodsOrder> goodsOrderList = this.dao().query(GoodsOrder.class,
				cnd.and("user_id", "in", userIdStrNew).and("company_id", "!=", "0"));
		if (goodsOrderList.size() != 0) {
			for (GoodsOrder goodsOrder : goodsOrderList) {
				deliveryPriceSum.add(new BigDecimal(goodsOrder.getDeliveryPrice()));
			}
		}
		return deliveryPriceSum;
	}

	public QueryResult getSpsrList(String createTimeBegin, String createTimeEnd, CompanyUser companyUser, int pageNum,
			int numPerPage) {
		Company company = this.dao().fetch(Company.class, Cnd.where("id", "=", companyUser.getCompanyId()));
		//先查出来该社区服务站下面的所有楼栋的ID
		List<VCompanyCommunity> vCompanyCommunityList = this.dao().query(VCompanyCommunity.class,
				Cnd.where("company_id", "=", companyUser.getId()));
		String buildingIdStr = "";
		for (VCompanyCommunity vCompanyCommunity : vCompanyCommunityList) {
			buildingIdStr += vCompanyCommunity.getBuildingId() + ",";
		}
		String buildingIdStrNew = "";
		if (buildingIdStr.equals("")) {
			buildingIdStrNew = "0";
		} else {
			buildingIdStrNew = buildingIdStr.substring(0, buildingIdStr.length() - 1);
		}
		//再查出来所有楼栋的所有用户
		List<ShopUserView> shopUserViewList = this.dao().query(ShopUserView.class,
				Cnd.where("buildingId", "in", buildingIdStrNew));
		String userIdStr = "";
		for (ShopUserView shopUserView : shopUserViewList) {
			userIdStr = shopUserView.getId() + ",";
		}
		String userIdStrNew = "";
		if (userIdStr.equals("")) {
			userIdStrNew = "0";
		} else {
			userIdStrNew = userIdStr.substring(0, userIdStr.length() - 1);
		}

		Pager pager = this.dao().createPager((pageNum < 1) ? 1 : pageNum,
				(numPerPage < 1) ? SystemContext.PAGE_SIZE : numPerPage);
		Cnd cnd = Cnd.where("user_id", "in", userIdStrNew).and("treeId", "=", "1")
				.and("create_time", ">=", createTimeBegin).and("create_time", "<=", createTimeEnd);
		List<OrderSupplierView> orderSupplierViewList = this.dao().query(OrderSupplierView.class, cnd, pager);
		if (pager != null) {
			pager.setRecordCount(this.dao().count(OrderSupplierView.class, cnd));
		}
		return new QueryResult(orderSupplierViewList, pager);
	}

	/**
	 * 供货商应付
	 */
	public void countAllSupplier() {
		Calendar dateCurr = Calendar.getInstance();
		int year = dateCurr.get(Calendar.YEAR);
		int month = dateCurr.get(Calendar.MONTH);
		dateCurr.set(year, month - 1, 1);
		/**
		 * Calendar.Date:表示一个月中的某天
		 * calendar.getActualMaximum(int field):返回指定日历字段可能拥有的最大值
		 */
		int actualMaximum = dateCurr.getActualMaximum(Calendar.DATE);
		if (month == 0) {
			year = year - 1;
			month = 12;
		}
		String startDate = "" + year + "-" + month + "-1 00:00:00";
		String endDate = "" + year + "-" + month + "-" + actualMaximum + " 23:59:59";
		Criteria cri = Cnd.cri();
		cri.where().and("deleteFlag", "=", 0);
		List<Supplier> list = this.dao().query(Supplier.class, cri);
		for (Supplier supplier : list) {
			String sql = "select sum(GOR.supplier_price*GOR.product_count) from order_supplier_view GOR where GOR.supplier_id="
					+ supplier.getId()
					+ " and GOR.status="
					+ Constants.ORDER_STATUS_DONE
					+ " and GOR.actual_arrive_date >='"
					+ startDate
					+ "' and GOR.actual_arrive_date < '"
					+ endDate
					+ "'";
			//					+ "' and order_type=" + Constants.PRODUCT_ORDER;
			SqlTemplate sqlTemplate = new SqlTemplate(this.dao());
			Double sum = sqlTemplate.queryForObject(sql, null, Double.class);
			if (sum == null)
				sum = 0d;
			OperatorsToSupplierAccounts ots = new OperatorsToSupplierAccounts();
			ots.setAccountPeriod(year + "-" + month);
			ots.setSupplierId(supplier.getId());
			ots.setToPaid(BigDecimal.valueOf(sum));
			ots.setCreateTime(new Date());
			ots.setCreateUser(0);
			ots.setRemark("系统生成");
			ots.setDeleteFlag(0);
			this.dao().insert(ots);
		}
	}

	/**
	 * 服务站应付
	 */
	public void countAllCompany() {
		Calendar dateCurr = Calendar.getInstance();
		int year = dateCurr.get(Calendar.YEAR);
		int month = dateCurr.get(Calendar.MONTH);
		dateCurr.set(year, month - 1, 1);
		/**
		 * Calendar.Date:表示一个月中的某天
		 * calendar.getActualMaximum(int field):返回指定日历字段可能拥有的最大值
		 */
		int actualMaximum = dateCurr.getActualMaximum(Calendar.DATE);
		if (month == 0) {
			year = year - 1;
			month = 12;
		}
		String startDate = "" + year + "-" + month + "-1 00:00:00";
		String endDate = "" + year + "-" + month + "-" + actualMaximum + " 23:59:59";
		Criteria cri = Cnd.cri();
		cri.where().and("deleteFlag", "=", 0);
		List<Company> list = this.dao().query(Company.class, cri);
		for (Company company : list) {
			Community communityReal = this.dao().fetch(Community.class, company.getCommunityId());
			List<CompanyToBuilding> building = new ArrayList<CompanyToBuilding>();
			//校区用户
			List<CompanyToSchoolUser> ids = new ArrayList<CompanyToSchoolUser>();

			List<Integer> builds = new ArrayList<Integer>();
			//需要查询的用户
			List<Integer> users = new ArrayList<Integer>();

			//是校区
			if (2 == communityReal.getCommunityType()) {
				ids = this.dao().query(CompanyToSchoolUser.class,
						Cnd.where(Cnd.exps("companyId", "=", company.getId())), null);
			}
			//找社区
			building = this.dao().query(CompanyToBuilding.class, Cnd.where("companyId", "=", company.getId()));

			for (CompanyToBuilding ctb : building)
				builds.add(ctb.getBuildingId());
			//社区用户
			if (builds != null && builds.size() > 0) {
				List<ShopUserView> query2 = this.dao().query(ShopUserView.class, Cnd.where("buildingId", "in", builds));
				for (ShopUserView suv : query2)
					users.add(suv.getId());
			}
			//校区用户
			for (CompanyToSchoolUser queryUser : ids)
				users.add(queryUser.getUserId());

			//实物分成
			Integer sharePercent = company.getSharePercent();
			//非实物分成
			//			int sharePercentVirtual = company.getSharePercentVirtual();
			if (sharePercent == null)
				sharePercent = 0;
			Double sum = 0d;
			Double sumDelivery = 0d;

			for (Integer uid : users) {
				//预定和现货的实物总价(只要线上的)
				String sql = "select sum(fodv.sell_price*fodv.product_count) from order_supplier_view fodv INNER JOIN supplier pro on fodv.supplier_id=pro.id where pro.offline_flag="
						+ Constants.ON_LINE
						+ " and fodv.user_id="
						+ uid
						+ " and fodv.status="
						+ Constants.ORDER_STATUS_DONE
						+ " and fodv.actual_arrive_date >='"
						+ startDate
						+ "' and fodv.actual_arrive_date < '"
						+ endDate
						+ "' and fodv.virtual_flag="
						+ Constants.VIRTUAL_NO_FLAG
						+ " and (fodv.order_type="
						+ Constants.PRODUCT_ORDER
						+ " or fodv.order_type=" + Constants.RESERVE_ORDER + ")";
				SqlTemplate sqlTemplate = new SqlTemplate(this.dao());
				Double one = sqlTemplate.queryForObject(sql, null, Double.class);
				if (one == null)
					one = 0d;
				sum += one;
				//预定和现货的非实物总价
				//				String sql2 = "select sum(sell_price*product_count) from order_supplier_view where user_id=" + uid
				//						+ " and status=" + Constants.ORDER_STATUS_DONE + " and actual_arrive_date >='" + startDate
				//						+ "' and actual_arrive_date < '" + endDate + "' and virtual_flag<>" + Constants.VIRTUAL_NO_FLAG
				//						+ " and (order_type=" + Constants.PRODUCT_ORDER + " or order_type=" + Constants.RESERVE_ORDER
				//						+ ")";
				//				Double one2 = sqlTemplate.queryForObject(sql2, null, Double.class);
				//				if (one2 == null)
				//					one2 = 0d;
				//				sumDelivery += one2;
				//配送费
				//			String sql2="select sum(delivery_price) from goods_order where user_id="+suv.getId()+" and status="+Constants.ORDER_STATUS_DONE+" and actual_arrive_date >='"+startDate+"' and actual_arrive_date < '"+endDate+"' and order_type="+Constants.PRODUCT_ORDER;
				//			Double oneDelivery = sqlTemplate.queryForObject(sql2,null, Double.class);
				//			if(oneDelivery==null)
				//				oneDelivery=0d;
				//			sumDelivery+=oneDelivery;
				//服务费
				//			String sql3="select sum(sell_price) from goods_order where user_id="+suv.getId()+" and status="+Constants.ORDER_STATUS_DONE+" and actual_arrive_date >='"+startDate+"' and actual_arrive_date < '"+endDate+"' and order_type="+Constants.SERVICE_ORDER;
				//			Double oneService = sqlTemplate.queryForObject(sql3,null, Double.class);
				//			if(oneService==null)
				//				oneService=0d;
				//			sumDelivery+=oneService;
			}

			BigDecimal total = BigDecimal.valueOf(sum * sharePercent / 100);
			//					.add(BigDecimal.valueOf(sumDelivery * sharePercentVirtual / 100));
			OperatorsToCompanyAccounts ots = new OperatorsToCompanyAccounts();
			ots.setAccountPeriod(year + "-" + month);
			ots.setCompanyId(company.getId());
			ots.setToPaid(total);
			ots.setCreateTime(new Date());
			ots.setCreateUser(0);
			ots.setRemark("系统生成商品总额");
			ots.setDeleteFlag(0);
			this.dao().insert(ots);
			//			OperatorsToCompanyAccounts ots2 = new OperatorsToCompanyAccounts();
			//			ots2.setAccountPeriod(year + "-" + month);
			//			ots2.setCompanyId(company.getId());
			//			ots2.setToPaid(BigDecimal.valueOf(sumDelivery * Integer.valueOf(sumDeliveryPercent) / 100));
			//			ots2.setCreateTime(new Date());
			//			ots2.setCreateUser(0);
			//			ots2.setRemark("系统生成服务总额");
			//			ots2.setDeleteFlag(0);
			//			this.dao().insert(ots2);
		}
	}

	public BigDecimal countSr(CompanyUser companyUser, Cnd cnd) {
		Company company = this.dao().fetch(Company.class, Cnd.where("id", "=", companyUser.getCompanyId()));
		//先查出来该社区服务站下面的所有楼栋的ID
		List<VCompanyCommunity> vCompanyCommunityList = this.dao().query(VCompanyCommunity.class,
				Cnd.where("company_id", "=", companyUser.getId()));
		String buildingIdStr = "";
		for (VCompanyCommunity vCompanyCommunity : vCompanyCommunityList) {
			buildingIdStr += vCompanyCommunity.getBuildingId() + ",";
		}
		String buildingIdStrNew = "";
		if (buildingIdStr.equals("")) {
			buildingIdStrNew = "0";
		} else {
			buildingIdStrNew = buildingIdStr.substring(0, buildingIdStr.length() - 1);
		}
		//再查出来所有楼栋的所有用户
		List<ShopUserView> shopUserViewList = this.dao().query(ShopUserView.class,
				Cnd.where("buildingId", "in", buildingIdStrNew));
		String userIdStr = "";
		for (ShopUserView shopUserView : shopUserViewList) {
			userIdStr = shopUserView.getId() + ",";
		}
		String userIdStrNew = "";
		if (userIdStr.equals("")) {
			userIdStrNew = "0";
		} else {
			userIdStrNew = userIdStr.substring(0, userIdStr.length() - 1);
		}

		//		BigDecimal sellPriceSumTrue = spsr();
		//BigDecimal sellPriceSumTrue = spsr();
		return null;
	}

	//计算该社区服务站商品收入的
	public BigDecimal spsr(Company company, String userIdStrNew, Cnd cnd) {
		//小区商品钱数(没乘小区分成百分比)
		BigDecimal sellPriceSum = new BigDecimal(0.0);
		//小区商品钱数(乘以小区分成百分比)
		BigDecimal sellPriceSumTrue = new BigDecimal(0.0);
		//商品运费钱数
		BigDecimal deliveryPriceSum = new BigDecimal(0.0);

		List<GoodsOrder> goodsOrderList = this.dao()
				.query(GoodsOrder.class,
						cnd.and("status", "!=", "0").and("status", "!=", 4).and("user_id", "in", userIdStrNew)
								.and("show_flag", "=", "1").and("order_type", "=", "1")
								.and("company_id", "=", company.getId()));
		for (GoodsOrder goodsOrder : goodsOrderList) {
			sellPriceSum.add(new BigDecimal(goodsOrder.getSellPrice()));
			deliveryPriceSum.add(new BigDecimal(goodsOrder.getDeliveryPrice()));
		}
		sellPriceSumTrue = sellPriceSum.multiply(new BigDecimal(company.getSharePercent()));
		return sellPriceSumTrue.add(deliveryPriceSum);
	}

	//计算社区服务费总收入
	public BigDecimal sqfwf(Company company, String userIdStrNew, Cnd cnd) {
		//小区服务费
		BigDecimal companyServiceSum = new BigDecimal(0.0);
		List<GoodsOrder> goodsOrderList = this.dao().query(
				GoodsOrder.class,
				cnd.and("user_id", "in", userIdStrNew).and("show_flag", "=", "1").and("order_type", "=", "2")
						.and("company_id", "=", company.getId()));
		for (GoodsOrder goodsOrder : goodsOrderList) {
			companyServiceSum.add(new BigDecimal(goodsOrder.getSellPrice()));
		}
		return companyServiceSum.multiply(new BigDecimal(0.9));
	}

	/**
	 * 取得服务站账目列表.
	 * 
	 * @param pageNumber
	 * @param keyword
	 * @return
	 */
	public QueryResult getCompanyAccountsList(int pageNumber, String accountPeriod, int companyId) {

		if (pageNumber <= 0) {
			pageNumber = 1;
		}

		// 拼接条件
		SqlExpressionGroup group = Cnd.exps("deleteFlag", "=", 0);

		// 账期
		if (accountPeriod != null && accountPeriod.length() > 0) {
			group = group.and("accountPeriod", "like", "%" + accountPeriod + "%");
		}

		// 供应商ID
		if (companyId > 0) {
			group = group.and("companyId", "=", companyId);
		}

		// 最大页数
		Pager pager = this.dao().createPager(pageNumber, Constants.LIST_ONE_PAGE_SIZE);

		// 查询记录总数
		int recordCount = this.dao().count(OperatorsToCompanyAccounts.class, Cnd.where(group));
		pager.setRecordCount(recordCount);

		// 没数据，直接返回
		if (recordCount == 0) {
			return new QueryResult(new ArrayList<OperatorsToCompanyAccounts>(0), pager);
		}

		// 计算页数
		int maxPageNumber = 0;
		if (recordCount % Constants.LIST_ONE_PAGE_SIZE == 0) {
			maxPageNumber = recordCount / Constants.LIST_ONE_PAGE_SIZE;
		} else {
			maxPageNumber = recordCount / Constants.LIST_ONE_PAGE_SIZE + 1;
		}
		if (pageNumber > maxPageNumber) {
			pager.setPageNumber(maxPageNumber);
		}

		// 查询
		List<OperatorsToCompanyAccounts> resultList = this.dao().query(OperatorsToCompanyAccounts.class,
				Cnd.where(group).desc("createTime"), pager); // 当前页面显示记录

		// 返回
		return new QueryResult(resultList, pager);
	}

	public List<StartEndDate> countAllSupplierByDate(Date startDateIn, Date endDateIn, SupplierUser supplierUser) {
		List<StartEndDate> startEndDateList = new ArrayList<StartEndDate>();
		List<String> strDates = countDate(startDateIn, endDateIn);
		Supplier supplier = this.dao().fetch(Supplier.class, Cnd.where("id", "=", supplierUser.getSupplierId()));
		for (String strDate : strDates) {
			String sql = "select sum(OD.supplier_price*OD.product_count) from order_detail OD INNER JOIN goods_order GOR ON GOR.ID=OD.order_id AND GOR.supplier_id="
					+ supplier.getId()
					+ " and GOR.status="
					+ Constants.ORDER_STATUS_DONE
					+ " and GOR.actual_arrive_date like '%" + strDate + "%'";
			SqlTemplate sqlTemplate = new SqlTemplate(this.dao());
			Double sum = sqlTemplate.queryForObject(sql, null, Double.class);
			if (sum == null) {
				sum = 0d;
			}
			StartEndDate startEndDate = new StartEndDate();
			startEndDate.setSupplierName(supplier.getSupplierName());
			startEndDate.setPrice(sum + "");
			startEndDate.setDate(strDate);
			startEndDateList.add(startEndDate);
		}

		return startEndDateList;
	}

	/**
	 * 服务站应付
	 */
	public List<StartEndDateCompany> countAllCompanyByDate(Date startDateIn, Date endDateIn, CompanyUser companyUser) {
		List<StartEndDateCompany> startEndDateCompanyList = new ArrayList<StartEndDateCompany>();
		List<String> strDates = countDate(startDateIn, endDateIn);
		Company company = this.dao().fetch(Company.class, Cnd.where("id", "=", companyUser.getCompanyId()));
		//实物分成
		Integer sharePercent = company.getSharePercent();
		if (sharePercent == null)
			sharePercent = 0;
		//非实物分成
		//		int sharePercentVirtual = company.getSharePercentVirtual();
		Community communityReal = this.dao().fetch(Community.class, company.getCommunityId());
		List<CompanyToBuilding> building = new ArrayList<CompanyToBuilding>();
		//校区用户
		List<CompanyToSchoolUser> ids = new ArrayList<CompanyToSchoolUser>();

		List<Integer> builds = new ArrayList<Integer>();
		//需要查询的用户
		List<Integer> users = new ArrayList<Integer>();

		//是校区
		if (2 == communityReal.getCommunityType()) {
			ids = this.dao().query(CompanyToSchoolUser.class, Cnd.where(Cnd.exps("companyId", "=", company.getId())),
					null);
		}
		//找社区
		building = this.dao().query(CompanyToBuilding.class, Cnd.where("companyId", "=", company.getId()));

		for (CompanyToBuilding ctb : building)
			builds.add(ctb.getBuildingId());
		//社区用户
		if (builds != null && builds.size() > 0) {
			List<ShopUserView> query2 = this.dao().query(ShopUserView.class, Cnd.where("buildingId", "in", builds));
			for (ShopUserView suv : query2)
				users.add(suv.getId());
		}
		//校区用户
		for (CompanyToSchoolUser queryUser : ids)
			users.add(queryUser.getUserId());
		String uids = "";
		for (Integer uid : users)
			uids += uid + ",";
		if (uids.length() > 0)
			uids = uids.substring(0, uids.length() - 1);
		for (String strDate : strDates) {
			Double sum = 0d;
			//			Double sumDelivery = 0d;
			//预定和现货的实物总价(只要线上供应商的)
			String sql = "select sum(fodv.sell_price*fodv.product_count) from order_supplier_view fodv INNER JOIN supplier pro on fodv.supplier_id=pro.id where pro.offline_flag="
					+ Constants.ON_LINE
					+ " and fodv.user_id in("
					+ uids
					+ ")"
					+ " and fodv.status="
					+ Constants.ORDER_STATUS_DONE
					+ " and fodv.actual_arrive_date like '%"
					+ strDate
					+ "%' and fodv.virtual_flag="
					+ Constants.VIRTUAL_NO_FLAG
					+ " and (fodv.order_type="
					+ Constants.PRODUCT_ORDER + " or fodv.order_type=" + Constants.RESERVE_ORDER + ")";
			SqlTemplate sqlTemplate = new SqlTemplate(this.dao());
			Double one = sqlTemplate.queryForObject(sql, null, Double.class);
			if (one == null)
				one = 0d;
			sum += one;
			//预定和现货的非实物总价（非实物不要钱）
			//			String sql2 = "select sum(sell_price*product_count) from order_supplier_view where user_id in(" + uids
			//					+ ")" + " and status=" + Constants.ORDER_STATUS_DONE + " and actual_arrive_date like '%" + strDate
			//					+ "%' and virtual_flag<>" + Constants.VIRTUAL_NO_FLAG + " and (order_type="
			//					+ Constants.PRODUCT_ORDER + " or order_type=" + Constants.RESERVE_ORDER + ")";
			//			Double one2 = sqlTemplate.queryForObject(sql2, null, Double.class);
			//			if (one2 == null)
			//				one2 = 0d;
			//			sumDelivery += one2;
			BigDecimal total = BigDecimal.valueOf(sum * sharePercent / 100);
			//					.add(BigDecimal.valueOf(sumDelivery * sharePercentVirtual / 100));
			StartEndDateCompany startEndDateCompany = new StartEndDateCompany();
			startEndDateCompany.setDate(strDate);
			startEndDateCompany.setPrice(total + "");
			startEndDateCompany.setCompanyName(company.getCompanyName());
			startEndDateCompanyList.add(startEndDateCompany);
		}
		return startEndDateCompanyList;
	}

	/**
	 * 得到两个日期之间相差的天数
	 */
	public List<String> countDate(Date startDate, Date endDate) {
		Calendar startCalendar = Calendar.getInstance();
		Calendar endCalendar = Calendar.getInstance();
		List<String> dataStrList = new ArrayList<String>();
		startCalendar.setTime(startDate);
		endCalendar.setTime(endDate);
		startCalendar.add(Calendar.DAY_OF_MONTH, -1);
		try {
			while (startCalendar.before(endCalendar)) {
				startCalendar.add(Calendar.DAY_OF_MONTH, 1);
				String startStr = DateUtil.toString(startCalendar.getTime(), "yyyy-MM-dd");
				dataStrList.add(startStr);
			}
			return dataStrList;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
}
